﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyZbContract;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyZbContract;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyZbContract
{
    /// <summary>
    /// 项目合同服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaProContract", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyZbContractService : IZyZbContractService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyZbContractEntity> _zyZbContractRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyZbContractService"/>类型的新实例
        /// </summary>
        public ZyZbContractService(
            ISqlSugarRepository<ZyZbContractEntity> zyZbContractRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyZbContractRepository = zyZbContractRepository;            
            _db = _zyZbContractRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取项目合同
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyZbContractEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyZbContractInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取项目合同列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyZbContractListQueryInput input)
        {
            var sidx = input.sidx == null ? "signingTime" : input.sidx;
            var data = await _db.Queryable<ZyZbContractEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.contractType), p => p.ContractType.Equals(input.contractType))
                .WhereIF(!string.IsNullOrEmpty(input.desPersonName), p => p.DesPersonName.Equals(input.desPersonName))
                .Select(it=> new 
                {
                    id = it.Id,
                    contractId=it.ContractId,
                    contractType=it.ContractType,
                    partyA=it.PartyA,
                    partyB=it.PartyB,
                    signingTime=it.SigningTime,
                    stage=it.Stage,
                    amount=it.Amount,
                    startTime=it.StartTime,
                    endTime=it.EndTime,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    lastHander=it.LastHander,
                    desPersonName=it.DesPersonName,
                    lastHanderMobile=it.LastHanderMobile,
                }).MergeTable().Select<ZyZbContractListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyZbContractListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建项目合同
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyZbContractCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyZbContractEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.ContractId = await _billRuleService.GetBillNumber("ZYHT");
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;  
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新项目合同
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyZbContractUpInput input)
        {
            var entity = input.Adapt<ZyZbContractEntity>();
            entity.Modifyer = _userManager.UserId;
            entity.ModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除项目合同
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyZbContractEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyZbContractEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
